from django.views import View
from django_redis import get_redis_connection
from django import http
import random
import logging

from . import constants
from utils.response_code import RETCODE
from verifications.libs.captcha.captcha import captcha
from verifications.libs.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import send_sms_code


# Create your views here.
class VerificationCode(View):
    def get(self, request, uuid):
        redis_conn = get_redis_connection('verify_code')
        text, image_code = captcha.generate_captcha()
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_VERIFY_CODE_EXPIRES, text)
        return http.HttpResponse(image_code, {'Content-type': 'image/jpg'})


class SMSCodeView(View):
    def get(self, request, mobile):
        redis_conn = get_redis_connection('verify_code')
        send_sms_flag = redis_conn.get('send_sms_code_flag_%s' % mobile)
        if send_sms_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': 'Sending verification code too frequently'})

        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        if not all([image_code_client, uuid]):
            return http.HttpResponseForbidden('Missing parameters')

        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': 'Image verification code expired'})

        redis_conn.delete('img_%s' % uuid)

        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': 'Incorrect image verification code'})

        sms_code = '%06d' % random.randint(0, 999999)
        redis_conn.setex('sms_%s' % mobile, constants.SMS_VERIFY_CODE_EXPIRES, sms_code)
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_VERIFY_CODE_EXPIRES // 60], constants.SMS_TEMPLATE_ID)
        send_sms_code.delay(mobile, sms_code)
        redis_conn.setex('send_sms_code_flag_%s' % mobile, constants.SMS_CODE_SEND_INTERVAL, 1)

        logger = logging.getLogger('django')
        logger.info(mobile + '_' + sms_code)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'SMS code sent successfully'})